package com.qinggeng.project.system.service.impl;

import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.CalendarAdjustUtils;
import com.qinggeng.project.system.domain.UserAccountRecordLotteryMonth;
import com.qinggeng.project.system.mapper.UserAccountRecordLotteryMonthMapper;
import com.qinggeng.project.system.service.UserAccountRecordLotteryMonthService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Date;

@Service
public class UserAccountRecordLotteryMonthServiceImpl  implements UserAccountRecordLotteryMonthService {
    @Resource
    private UserAccountRecordLotteryMonthMapper userAccountRecordLotteryMonthMapper;


    @Override
    public UserAccountRecordLotteryMonth checkUserAccountRecordLotteryMonth(UserAccountRecordLotteryMonth month) {
        Long userId=month.getUserId();
        if (null ==userId){
            throw  new CustomException("userID 不能为空");
        }
        UserAccountRecordLotteryMonth userAccountRecordLotteryMonth= getUserAccountRecordLotteryMonth(userId);
        if (null == userAccountRecordLotteryMonth){
            Date date=new Date();
            month.setCreateDate(date);
            month.setCreateTime(date);
            month.setUpdateTime(date);
            Instant instant = Instant.now();
            long timeStampMillis = instant.toEpochMilli();
            month.setCreateTimeStamp(timeStampMillis);
            month.setCreateMonth(CalendarAdjustUtils.getMonthToStr());
            month.setCreateYear(CalendarAdjustUtils.getYearToStr());
            userAccountRecordLotteryMonthMapper.insertSelective(month);
        }
        return userAccountRecordLotteryMonth;
    }

    @Override
    public UserAccountRecordLotteryMonth getUserAccountRecordLotteryMonth(Long userId) {
        Example example =new Example(UserAccountRecordLotteryMonth.class);
        example.createCriteria()
                .andEqualTo("userId",userId)
                .andEqualTo("status",0)
                .andEqualTo("delFlag",0)
                .andEqualTo("createMonth", CalendarAdjustUtils.getMonthToStr());
        return userAccountRecordLotteryMonthMapper.selectOneByExample(example);
    }

    @Override
    public boolean updateAccountRecordLotteryMonthCalculation(Long id) {
        UserAccountRecordLotteryMonth month=new UserAccountRecordLotteryMonth();
        month.setId(id);
        month.setCalculation(0);
        return userAccountRecordLotteryMonthMapper.updateByPrimaryKeySelective(month)>=1;
    }
}
